package djboom.materials.display.page.work1 {
	import djboom.materials.Work;
	import djboom.materials.core.BitmapDataCore;
	import djboom.materials.core.DataCore;
	import djboom.materials.display.devices.Scales;
	import djboom.materials.display.elements.Instruction;
	import djboom.materials.display.elements.TableData;
	import djboom.materials.display.elements.TableDataCell;
	import djboom.materials.display.elements.Window;
	import djboom.materials.display.page.Page;
	import djboom.materials.events.InstructionEvent;
	import djboom.materials.events.PageEvent;
	import djboom.materials.events.TableDataCellEvent;
	import djboom.materials.events.WindowEvent;

	import com.greensock.TweenLite;
	import com.greensock.easing.Cubic;

	import org.casalib.display.CasaBitmap;
	import org.casalib.display.CasaSprite;
	import org.casalib.util.StageReference;

	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.geom.Rectangle;

	/**
	 * .
	 * <br>
	 * 
	 * @author DJ BooM 
	 * @since 28.04.2010
	 * 
	 */

	public class Page3 extends Page {

		// ----------------------------------------------------------------------------
		// Константы класса.
		// ----------------------------------------------------------------------------

		private static var COUNTER_MATERIAL:int = 0;

		// ----------------------------------------------------------------------------
		// Свойства класса.
		// ----------------------------------------------------------------------------

		private var _heightFall:Number;

		private var _instruction:Instruction;
		private var _scales:Scales;
		private var _materialsList:XMLList;
		private var _sampleMaterialXML:XML;
		private var _sampleMaterialBitmap:CasaBitmap;
		private var _sampleMaterial:CasaSprite;

		private var _tableDataXML:XML;
		private var _tableData:TableData;

		private var _window:Window;

		// ----------------------------------------------------------------------------
		// Конструктор.
		// ----------------------------------------------------------------------------

		public function Page3() {
			super();
		}	 

		// ----------------------------------------------------------------------------
		// Методы класса.
		// ----------------------------------------------------------------------------

		private function createTableDataXML():void {
			_tableDataXML = <tabledata></tabledata>;
            
			for each (var materialXML:XML in _materialsList) {
				var materialName:String = materialXML.attribute("name").toString();
				var materialLength:String = materialXML.attribute("length").toString();
				var materialBase:String = materialXML.attribute("base").toString();
				var materialHeight:String = materialXML.attribute("height").toString();
				var materialWeight:String = materialXML.attribute("weight").toString();
                
				var amount:String = materialXML.attribute("amount").toString();
				var averageHardness_G:String = materialXML.attribute("averageHardness_G").toString();
				var averageHardness_KG:String = materialXML.attribute("averageHardness_KG").toString();
                
				_tableDataXML.appendChild(<row>
                    <cell align="left" width="269">
                      <data>{materialName}</data>
                    </cell>
                    <cell align="center" width="48">
                      <data>{materialLength}</data>
                    </cell>
                    <cell align="center" width="50">
                      <data>{materialBase}</data>
                    </cell>
                    <cell align="center" width="50">
                      <data>{materialHeight}</data>
                    </cell>
                    <cell align="center" width="72">
                      <data> </data>
                      <checkData>{materialWeight}</checkData>
                    </cell>
                    <cell align="center" width="86">
                      <data> </data>
                      <checkData>{amount}</checkData>
                    </cell>
                    <cell align="center" width="118">
                      <data> </data>
                      <checkData>{averageHardness_G}</checkData>
                    </cell>
                    <cell align="center" width="118">
                      <data> </data>
                      <checkData>{averageHardness_KG}</checkData>
                    </cell>
                </row>);
			}
		}

		/**
		 * Создаем образец в зависимости от текущего этапа работы.
		 * 
		 */

		private function createMaterial():void {
			_sampleMaterialXML = _materialsList[COUNTER_MATERIAL] as XML;
			
			_sampleMaterialBitmap = new CasaBitmap(BitmapDataCore.getBitmapData(_sampleMaterialXML.attribute("sampleBitmapData").toString()));
			
			_sampleMaterial = new CasaSprite();
			_sampleMaterial.x = 100;			_sampleMaterial.y = Work.HEIGHT - 52 - _sampleMaterialBitmap.height;
			_sampleMaterial.buttonMode = true;
			_sampleMaterial.useHandCursor = true;
			_sampleMaterial.tabEnabled = false;
			_sampleMaterial.addChild(_sampleMaterialBitmap);
			addChild(_sampleMaterial);
			
			_sampleMaterial.addEventListener(MouseEvent.MOUSE_DOWN, setupDragSample);
			_sampleMaterial.addEventListener(MouseEvent.MOUSE_UP, stopDragSprite);
		}

		private function setupDragSample(event:MouseEvent):void {
			dragSprite();
		}

		/**
		 * Таскаем объект.
		 * 
		 */

		private function dragSprite(event:MouseEvent = null):void {
			_heightFall = Work.HEIGHT - _sampleMaterial.height - 52;
			
			_sampleMaterial.startDrag(false, new Rectangle(3, 82 + _instruction.height, Work.WIDTH - 6 - _sampleMaterial.width, Work.HEIGHT - 82 - _instruction.height - 52 - _sampleMaterial.height));
            
			StageReference.getStage().addEventListener(MouseEvent.MOUSE_UP, captureMouseUp);
		}

		/**
		 * Останавливаем таскание объекта.
		 * 
		 */

		private function stopDragSprite(event:MouseEvent = null):void {
			_sampleMaterial.stopDrag();
            
			StageReference.getStage().removeEventListener(MouseEvent.MOUSE_UP, captureMouseUp);
			
			var centerScale:Number = ((926 - 732) / 2 + 732) - _sampleMaterial.width * 0.5;
			var limitX:int = 20;
			
			if (_sampleMaterial.x <= (centerScale + limitX) && _sampleMaterial.x >= (centerScale - limitX) && _sampleMaterial.y > 80 && _sampleMaterial.y < (559 - _sampleMaterial.height) + 5) {
				_sampleMaterial.buttonMode = false;
				_sampleMaterial.useHandCursor = false;
				
				_sampleMaterial.removeEventListener(MouseEvent.MOUSE_DOWN, setupDragSample);
				_sampleMaterial.removeEventListener(MouseEvent.MOUSE_UP, stopDragSprite);
						
				TweenLite.to(_sampleMaterial, 0.4, {x: centerScale, y: 559 - _sampleMaterial.height, ease: Cubic.easeIn, onComplete: setupScale});
			} else {
				var timeFall:Number = (_heightFall - _sampleMaterial.y) / 550;
						
				TweenLite.to(_sampleMaterial, timeFall, {y: _heightFall, ease: Cubic.easeIn});
			}
		}

		/**
		 * Реализация функции ReleaseOutside.
		 * 
		 */

		private function captureMouseUp(event:MouseEvent):void {
			if (event.target == _sampleMaterial || _sampleMaterial.contains(DisplayObject(event.target))) {
			} else {
				stopDragSprite();
			}
		}

		private function setupScale():void {
			_scales.animateWeightDown();
			TweenLite.to(_sampleMaterial, 0.5, {y: _sampleMaterial.y + 10, ease: Cubic.easeOut, onComplete: setupScaleWeight});
		}

		private function setupScaleWeight():void {
			_scales.setupWeight(_sampleMaterialXML.attribute("weight").toString() + ".00");
			
			_instruction.nextInstruction();
		}

		private function lightTableCell(event:InstructionEvent):void {
			_tableData.y = 82 + _instruction.scrollHeight;
			_tableData.enableCell(COUNTER_MATERIAL + event.cellName);
			
			TweenLite.to(_tableData, 0.5, {scrollRect: {x: 0, y: 0, width: _tableData.width, height: _tableData.scrollHeight}, ease: Cubic.easeInOut, delay: 1});
		}

		private function inputError(event:TableDataCellEvent):void {
			lockPage();
            
			_window = new Window();
			_window.addEventListener(WindowEvent.CLOSE, repeatEnableCell);
			_window.init("Внимание!", "Введены некорректные данные");
			addChild(_window);
		}

		private function repeatEnableCell(event:WindowEvent):void {
			unlockPage();
            
			if (_window != null) {
				_window.destroy();
				_window = null;
			}
            
			_tableData.repeatEnableCell();
		}

		private function inputSuccess(event:TableDataCellEvent):void {
			var inputCell:Boolean = _instruction.checkInputCell();
			
			if (!inputCell) TweenLite.to(_tableData, 0.5, {scrollRect: {x: 0, y: _tableData.scrollHeight, width: _tableData.width, height: 0}, ease: Cubic.easeInOut}); 
            
			_instruction.nextInstruction();
		}

		private function inputLastCell(event:TableDataCellEvent):void {
			var pageEvent:PageEvent = new PageEvent(PageEvent.CHANGE);
			pageEvent.pageName = Page.WORK_1_PAGE_4;            
			dispatchEvent(pageEvent);
		}

		private function inputLastCellRow(event:TableDataCellEvent):void {
			COUNTER_MATERIAL++;
            
			TweenLite.to(_tableData, 0.5, {scrollRect: {x: 0, y: _tableData.scrollHeight, width: _tableData.width, height: 0}, ease: Cubic.easeInOut});
            
			_instruction.nextInstruction();
            
			_scales.clearScale();
            
			_sampleMaterialXML = null;
            
			_sampleMaterialBitmap.destroy();
			_sampleMaterialBitmap = null;
            
			_sampleMaterial.destroy();
			_sampleMaterial = null;
            
			createMaterial();
		}

		// ----------------------------------------------------------------------------
		// Публичные методы.
		// ----------------------------------------------------------------------------

		override public function init():void {
			// Создаем заголовок страницы.
			createTitleWork("Определение средней плотности на образцах правильной геометрической формы", 1);
			
			// Создаем инструкцию.
			_instruction = new Instruction(DataCore.INSTRUCTION_WORK_1.child("instruction"));
			_instruction.addEventListener(InstructionEvent.LIGHT_CELL, lightTableCell);			addChild(_instruction);
			
			_scales = new Scales("0.00", "ПРЕДЕЛЬНАЯ НАГРУЗКА 5000 г");
			_scales.x = 700;			_scales.y = 554;
			addChild(_scales);
			
			_materialsList = DataCore._materialsWork1XML.child("material").(@select == "true");
			
			createTableDataXML();
			
			_tableData = new TableData(BitmapDataCore.getBitmapData(BitmapDataCore.WORK1_TABLEDATA), _tableDataXML, new Point(16, 68), TableDataCell.CELL_FORMAT_19PX);
			_tableData.x = 30;
			_tableData.y = 82 + _instruction.scrollHeight;
			_tableData.addEventListener(TableDataCellEvent.INPUT_ERROR, inputError);
			_tableData.addEventListener(TableDataCellEvent.INPUT_SUCCESS, inputSuccess);			_tableData.addEventListener(TableDataCellEvent.INPUT_LAST_CELL_ROW, inputLastCellRow);			_tableData.addEventListener(TableDataCellEvent.INPUT_LAST_CELL, inputLastCell);
			_tableData.scrollRect = new Rectangle(0, _tableData.height, _tableData.width, 0);
			addChild(_tableData);
			
			createMaterial();            
		}

		/**
		 * Очистка страницы.
		 * 
		 */

		override protected function clearPage(event:Event):void {
			super.clearPage(event);
			
			_materialsList = null;
			
			_sampleMaterialXML = null;
			
			if (_sampleMaterialBitmap != null) {
				_sampleMaterialBitmap.destroy();
				_sampleMaterialBitmap = null;  
			}
			
			if (_sampleMaterial != null) {
				_sampleMaterial.destroy();
				_sampleMaterial = null;  
			}
			
			_tableData.destroy();
			_tableData = null;
			
			_instruction.destroy();
			_instruction = null;
			
			if (_window != null) {
				_window.destroy();
				_window = null;
			}
			
			_scales.destroy();
			_scales = null;
		}
        
		// ----------------------------------------------------------------------------
        // Публичные свойства.
        // ----------------------------------------------------------------------------
	}
}
